import React, { ReactElement,useState,useEffect  } from 'react'
import {Select,Input,Button,DatePicker ,Space,Table,Divider,Pagination ,Radio ,Drawer ,Form,Checkbox,message } from 'antd'
import {connect,useDispatch,useSelector} from "react-redux"

import api  from './../../apijlf/api.js'
import UserAddModal  from './sub/UserAddModal.jsx'


const {Option }=Select
const { RangePicker } = DatePicker
const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
  },
  {
    title: '性别',
    render:(val)=>{
      if(val.ssex=="0"){
        return "男"
      }else if(val.ssex=="1"){
        return "女"
      }else if(val.ssex=="2"){
        return "保密"
      }
    }
  },
  {
    title: '邮箱',
    dataIndex: 'email',
  },
  {
    title: '部门',
    dataIndex: 'deptName',
  },
  {
    title: '电话',
    dataIndex: 'mobile',
  },
  {
    title: '状态',
    render:(val)=>{
      if(val.status=="1"){
        return "有效"
      }else if(val.status=="0"){
        return "锁定"
      }
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',
    render: (text) => (
        <>
            <Button type='dashed' onClick={() => this.delUser(text)} >删除</Button>
        </>
    ),
}
];

export default function User(props) {
  //模态框开始
  const [visible, setVisible] = useState(false);
  const [placement, setPlacement] = useState('right');

  const showDrawer = () => {
    setVisible(true);
  };

  const onChange = (e) => {
    setPlacement(e.target.value);
  };

  const onClose = () => {
    setVisible(false);
  };
  //模态框结束


  const [searchOn,setSearchOn]=useState({})
  const dispatch = useDispatch()
  //得到仓库所有用户数据，以及总页数数据
  const result =useSelector(state=>state.userRc)

  const [selectionType, setSelectionType] = useState('checkbox');
  //复选框选中哪些要删除
  const [delDatas,setDelDatas]=useState([])

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setDelDatas(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  //删除用户
  const delData=()=>{
    dispatch({
      type:'delUser',
      payload:delDatas
    })
    message.success('删除成功')
      getAllusers()

   
  }

   //选择部门
    const  handleChange=(e)=> {
      setSearchOn({
        ...searchOn,
        deptId:e
      })
      }

      //页面一进来执行
      useEffect(()=>{
        //获取所有用户数据
        getAllusers()
        //获取所有部门数据
        dispatch({
          type:'getDept',
        })
      },[])
      //获取所有用户
      const getAllusers=()=>{
        dispatch({
          type:'getUser',
          payload:{pageSize:'10',pageNum:'1'}
        })
      }

      //切换每页显示多少时触发
    const showPz =(current,size)=>{
      dispatch({
        type:'getUser',
        payload:{pageSize:size,pageNum:current}
      })
    }
    //点击那一页的回调
    const showChangPz = (page,pageSize)=>{
      dispatch({
        type:'getUser',
        payload:{pageSize:pageSize,pageNum:page}
      })
    }
    //搜索
    const searchData=()=>{
      console.log(searchOn);
      dispatch({
        type:'getUser',
        payload:searchOn
      })
    }
    //输入用户名的回调
    const inputUser=(e)=>{
      setSearchOn({
        ...searchOn,
        username:e.target.value
      })
    }
    //选择日期的回调
    const inputTime=(value)=>{
      if(value){
        setSearchOn({
          ...searchOn,
          createTimeFrom:value[0]._d.toLocaleDateString().replaceAll('/','-'),
          createTimeTo:value[1]._d.toLocaleDateString().replaceAll('/','-')
        })  
      }else {
        setSearchOn({
          ...searchOn,
          createTimeFrom:'',
          createTimeTo:''
        }) 
      }
    }
    return (
        <>
        <div style={{display:'flex' ,  alignItems: 'center' ,marginBottom: '20px' }}>
        <label htmlFor="">部门：</label>
        <Select defaultValue="请选择部门" style={{ width: 120 }} onChange={handleChange}>
          {result.dept.map(item=>{
            return (
              <Option value={item.id} key={item.id}>{item.title}</Option>
            )
          })}
         </Select>
         &nbsp; &nbsp;
         <label htmlFor="">用户名：</label>
         <Input placeholder="请输入用户名" style={{width:300}} onChange={inputUser} />
         &nbsp; &nbsp;
         <label htmlFor="">创建时间：</label>
         <Space direction="vertical" size={12} >
                <RangePicker onChange={inputTime} format='YYYY-MM-DD'/>
        </Space>
        &nbsp; &nbsp;
        <Button type="primary" onClick={searchData}>搜索</Button>
        </div>
        <Button onClick={showDrawer}>新增</Button>
        &nbsp; &nbsp;
        <Button  onClick={delData}>删除</Button>
        <Table
        style={{marginTop:'20px' }}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
        columns={columns}
        dataSource={result.users}
        rowKey='userId'
        pagination={{
          total:result.total,
          showTotal:(total, range) => `${range[0]}-${range[1]}条  共 ${total} 条记录`,
          defaultPageSize:10,
          defaultCurrent:1,
          onShowSizeChange:showPz,
          showSizeChanger:true,
          onChange:showChangPz,
          pageSizeOptions:[5,10,15,20]
        }}
      />   


      <Drawer
        title="新增用户"
        placement={placement}
        width={500}
        onClose={onClose}
        visible={visible}
        extra={
          <Space>
            <Button onClick={onClose}>Cancel</Button>
            <Button type="primary" onClick={onClose}>
              OK
            </Button>
          </Space>
        }
      >
        <UserAddModal setVisible={setVisible} getAllusers={getAllusers}></UserAddModal>
      </Drawer>
    

        </>
    )
}
